import type { Context } from 'hono'
import { UserService } from '../services/user.service.js'
import { userSchema, loginSchema } from '../schemas/user.schema.js'
import { z } from 'zod'

export class UserController {
    static async register(c: Context) {
        try {
            const body = await c.req.json()
            const { email, password, name } = userSchema.parse(body)
            const result = await UserService.register(email, password, name)
            return c.json(result)
        } catch (error) {
            if (error instanceof z.ZodError) {
                return c.json({ error: '输入数据验证失败', details: error.errors }, 400)
            }
            if (error instanceof Error) {
                return c.json({ error: error.message }, 400)
            }
            return c.json({ error: '注册失败' }, 500)
        }
    }

    static async login(c: Context) {
        try {
            const body = await c.req.json()
            const { email, password } = loginSchema.parse(body)
            const result = await UserService.login(email, password)
            return c.json(result)
        } catch (error) {
            if (error instanceof z.ZodError) {
                return c.json({ error: '输入数据验证失败', details: error.errors }, 400)
            }
            if (error instanceof Error) {
                return c.json({ error: error.message }, 400)
            }
            return c.json({ error: '登录失败' }, 500)
        }
    }

    static async getProfile(c: Context) {
        const payload = c.get('jwtPayload')
        const user = await UserService.getProfile(payload.userId)
        return c.json(user)
    }
} 